package com.epfresh.supplier.activity;

import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.epfresh.api.constant.AppSupplyRouterConstant;
import com.epfresh.api.global.BaseApplication;
import com.epfresh.api.global.*;
import com.epfresh.api.entity.RequestEntitySupply;
import com.epfresh.api.entity.ResponseEntity;
import com.epfresh.api.entity.StatusEntity;
import com.epfresh.api.helper.ApplicationHelper;

import com.epfresh.api.global.BaseActivity;
import com.epfresh.api.http.OnRequestListener;
import com.epfresh.api.utils.T;
import com.epfresh.supplier.R;
import com.epfresh.supplier.entity.CustomerAddItem;
import com.epfresh.supplier.entity.CustomerGroupItem;
import com.epfresh.supplier.entity.CustomerItem;
import com.epfresh.supplier.entity.CustomerPhone;
import com.epfresh.supplier.entity.SaveEntity;
import com.epfresh.supplier.entity.SaveModifyEntity;
import com.epfresh.supplier.widget.ViewVariable;
import com.google.gson.Gson;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


public class CustomerEditAddActivity extends BaseActivity implements ViewVariable {

    private String mAction;
    private CustomerItem mEditCustomerItem;
    private TextView mTvTitle;
    private EditText mEtEditAddName;
    private EditText mEtEditAddTel;
    private EditText mEtEditAddCompany;
    private LinearLayout mLlGroups;
    private EditText mEtEditAddRemark;
    private List<CustomerAddItem> addCustomer = new ArrayList<>();
    private Button mBtnSave;
    private TextView mTvGroupEdit;
    private TextView mTvGroupAdd;
    private TextView mTvEditAddGroupName;
    private TextView mTvEditAddAdressNo;
    private CustomerGroupItem mGroupItem;
    private String mAccountId = "";
    private String mEnterCustomerActivity;
    private View mGroupAdd;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_customer_edit_add);
        initView();
        initData();
    }

    @Override
    protected View getToolBar() {
        return null;
    }

    private void initData() {
        mAction = getIntent().getAction();
        switch (mAction) {
            case CUSTOMER_DETAIL_ACTIVITY:
                mTvTitle.setText("编辑客户");
                mEditCustomerItem = getIntent().getParcelableExtra("CustomerItem");
                String addressNo = getIntent().getStringExtra("addressNo");
                mEtEditAddTel.setEnabled(false);
                findViewById(R.id.ll_phone).setOnClickListener(this);
                mEtEditAddName.setText(mEditCustomerItem.getName());
                mEtEditAddTel.setText(mEditCustomerItem.getPhone());
                mEtEditAddCompany.setText(mEditCustomerItem.getOrg());
                if (getIntent().getIntExtra("groupSize", 0) > 1) {
                    mLlGroups.setVisibility(View.VISIBLE);
                    mTvGroupEdit.setVisibility(View.VISIBLE);
                    mGroupAdd.setVisibility(View.GONE);
                    mTvEditAddGroupName.setText(mEditCustomerItem.getGroupName());
                } else {
                    mLlGroups.setVisibility(View.GONE);
                }
                if ("0".equals(addressNo)) {
                    mTvEditAddAdressNo.setText("无");
                } else {
                    mTvEditAddAdressNo.setText(addressNo + "个");
                }
                mEtEditAddRemark.setText(mEditCustomerItem.getRemark());
                checkNameAndTel();
                break;
            case CUSTOMER_INFO_ACTIVITY:
                mTvTitle.setText("新增客户");
                mEnterCustomerActivity = getIntent().getStringExtra("enterCustomerActivity");
                mEtEditAddTel.setEnabled(true);
                if (getIntent().getIntExtra("groupSize", 0) > 1) {
                    mLlGroups.setVisibility(View.VISIBLE);
                    mTvGroupEdit.setVisibility(View.GONE);
                    mGroupAdd.setVisibility(View.VISIBLE);
                } else {
                    mLlGroups.setVisibility(View.GONE);
                }
                break;
            case CUSTOMER_GROUP_CONTANCT_ACTIVITY:
                mTvTitle.setText("新增客户");
                mGroupItem = getIntent().getParcelableExtra("GroupItem");
                mEnterCustomerActivity = getIntent().getStringExtra("enterCustomerActivity");
                mEtEditAddTel.setEnabled(true);
                if (getIntent().getIntExtra("groupSize", 0) > 1) {
                    mLlGroups.setVisibility(View.VISIBLE);
                    mTvGroupEdit.setVisibility(View.GONE);
                    mGroupAdd.setVisibility(View.VISIBLE);
                    mTvEditAddGroupName.setText(mGroupItem.getGroupName());
                } else {
                    mLlGroups.setVisibility(View.GONE);
                }
                break;
        }

    }

    private void initView() {
        mTvTitle = (TextView) findViewById(R.id.tv_edit_add_title);
        mEtEditAddName = (EditText) findViewById(R.id.et_layout_name);
        mEtEditAddTel = (EditText) findViewById(R.id.et_layout_tel);
        mEtEditAddCompany = (EditText) findViewById(R.id.et_layout_company);
        mLlGroups = (LinearLayout) findViewById(R.id.ll_layout_choose_group);
        mTvGroupEdit = (TextView) findViewById(R.id.tv_layout_group_edit);
        mTvGroupAdd = (TextView) findViewById(R.id.tv_layout_group_add);
        mGroupAdd = findViewById(R.id.rl_layout_group_add);
        mTvEditAddGroupName = (TextView) findViewById(R.id.tv_layout_group);
        mTvEditAddAdressNo = (TextView) findViewById(R.id.tv_layout_no);
        mEtEditAddRemark = (EditText) findViewById(R.id.et_layout_remark);
        mBtnSave = (Button) findViewById(R.id.btn_edit_add_save);

        mEtEditAddTel.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void afterTextChanged(Editable editable) {
                switch (mAction) {
                    case CUSTOMER_INFO_ACTIVITY:
                    case CUSTOMER_GROUP_CONTANCT_ACTIVITY:
                        String tel = mEtEditAddTel.getText().toString().trim();
                        if (11 == tel.length()) {
                            getAddressNo(tel);
                        }
                        break;
                }
            }
        });
        findViewById(R.id.back_ll).setOnClickListener(this);
        findViewById(R.id.ll_layout_choose_group).setOnClickListener(this);
        mBtnSave.setOnClickListener(this);
        findViewById(R.id.rl_layout_address).setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        super.onClick(v);
        switch (v.getId()) {
            case R.id.ll_phone:
                toast("客户手机号不可修改");
                break;
            case R.id.btn_edit_add_save:
                if (checkNameAndTel()) {
                    if (CUSTOMER_DETAIL_ACTIVITY.equals(mAction)) {
                        //修改保存
                        intoEditSave();
                    } else {
                        intoAddSave();
                    }
                }
                break;
            case R.id.ll_layout_choose_group:
                intoGroup();
                break;
            case R.id.back_ll:
                setResult(0x002);
                finish();
                break;
            case R.id.rl_layout_address:
                intoDelivery();
                break;
        }
    }


    private void getAddressNo(String tel) {
        RequestEntitySupply<Map<String, Object>> data = new RequestEntitySupply<>();
        data.setCmd(AppSupplyRouterConstant.cmd_account_customer_phoneAdd);
        Map<String, Object> map = new HashMap<>();
        map.put("phone", tel);
        map.put("merchantId",BaseApplication.getInstance().getMerchantId());
        data.setParameters(map);
        request(data, AppSupplyRouterConstant.cmd_account_customer_phoneAdd, addPhoneRequestListener);
    }
    OnRequestListener<CustomerPhone> addPhoneRequestListener = new OnRequestListener<CustomerPhone>() {
        @Override
        public CustomerPhone jsonToObj(String responseStr) {
            return new Gson().fromJson(responseStr, CustomerPhone.class);
        }

        @Override
        public void onFail(int failCode, Object arg, Object tag) {


        }

        @Override
        public void onResponseError(int failCode, Object arg, Object tag) {
        }

        @Override
        public void onStart(Object tag) {

        }

        @Override
        public void onResponse(ResponseEntity<CustomerPhone> response, Object tag) {
            CustomerPhone phone = response.getResponseElement();
            if (phone.isSuccess()) {
                if (!TextUtils.isEmpty(phone.getNum()) && !"0".equals(phone.getNum())) {
                    mTvEditAddAdressNo.setText(phone.getNum() + "个");
                } else {
                    mTvEditAddAdressNo.setText("无");
                }
                mAccountId = TextUtils.isEmpty(phone.getAccountId())?"":phone.getAccountId();
                return;
            }
        }
    };
    private void intoGroup() {
        Intent intent = new Intent(this, CustomerGroupActivity.class);
        intent.setAction(CUSTOMER_EDIT_ADD_ACTIVITY);
        startActivityForResult(intent, 1000);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        switch (requestCode) {
            case 1000:
                if (RESULT_OK == resultCode) {
                    mGroupItem = data.getParcelableExtra("GroupItem");
                    mTvEditAddGroupName.setText(TextUtils.isEmpty(mGroupItem.getGroupName()) ? "" : mGroupItem.getGroupName());
                }
                break;
        }
    }

    private boolean checkNameAndTel() {
        boolean b = true;
        if (getIntent().getIntExtra("groupSize", 0) > 1) {
            String group = mTvEditAddGroupName.getText().toString().trim();
            if (TextUtils.isEmpty(group)) {
                toast("请选择分组");
                b = false;
            }
        }

        String account = mEtEditAddTel.getText().toString().trim();
        if (TextUtils.isEmpty(account)) {
            toast("请输入手机号");
            b = false;
        }

        if (account.length() != 11) {
            toast("请输入合法的手机号");
            b = false;
        }
        String name = mEtEditAddName.getText().toString().trim();
        if (TextUtils.isEmpty(name)) {
            toast("请输入姓名");
            b = false;
        }

        return b;
    }

    boolean isAddCustomer;
    private void intoAddSave() {
        if (isAddCustomer){
            return;
        }
        getTerminalData();
        RequestEntitySupply<Map<String, Object>> data = new RequestEntitySupply<>();
          data.setCmd(AppSupplyRouterConstant.cmd_account_customer_add);
        Map<String, Object> map = new HashMap<>();
        map.put("customerModels", addCustomer);
        data.setParameters(map);
        request(data, AppSupplyRouterConstant.cmd_account_customer_add, addRequestListener);
    }

    OnRequestListener<SaveEntity> addRequestListener = new OnRequestListener<SaveEntity>() {
        @Override
        public SaveEntity jsonToObj(String responseStr) {
            return new Gson().fromJson(responseStr, SaveEntity.class);
        }

        @Override
        public void onFail(int failCode, Object arg, Object tag) {

            isAddCustomer = false;

        }

        @Override
        public void onResponseError(int failCode, Object arg, Object tag) {
            isAddCustomer = false;
        }

        @Override
        public void onStart(Object tag) {
            isAddCustomer = true;
        }

        @Override
        public void onResponse(ResponseEntity<SaveEntity> response, Object tag) {
            SaveEntity responseElement = response.getResponseElement();
            isAddCustomer = false;
            if (responseElement.isSuccess()) {
                toast("添加成功");
                // 保存成功 返回到客户详情页面
                /*
                     if (HOME_ACTIVITY.equals(mEnterCustomerActivity)) {
                            } else if (CART_ACTIVITY.equals(mEnterCustomerActivity) || BILLING_CHECK_ACTIVITY.equals(mEnterCustomerActivity)) {
                                RxBus.post(ARouter.BUS_GET_CUSTOMER_ITEM, saveEntity.getCustomer().get(0));
                                RxBus.post(ARouter.BUS_TAG_CUSTOMER_FINISH, "");
                            }
                *
                * */
                setResult(0x001);
                finish();
                return;
            }
            T.toast("添加出现异常，请稍后再试");
        }
    };


    private void getTerminalData() {
        addCustomer.clear();
        CustomerAddItem item = new CustomerAddItem();
        item.setMerchantId(BaseApplication.getInstance().getMerchantId());
        item.setName(mEtEditAddName.getText().toString().trim());
        item.setPhone(mEtEditAddTel.getText().toString().trim());
        item.setOrg(mEtEditAddCompany.getText().toString().trim());
        item.setRemark(mEtEditAddRemark.getText().toString().trim());

        if (getIntent().getIntExtra("groupSize", 0) < 1) {
            item.setGroupId("");
        } else {
            if (null != mGroupItem) {
                item.setGroupId(mGroupItem.getGroupId());
            }
        }
        addCustomer.add(item);
    }

    /**
     * 提交修改
     */
    private void intoEditSave() {
        RequestEntitySupply<Map<String, String>> data = new RequestEntitySupply<>();
        data.setCmd(AppSupplyRouterConstant.cmd_account_customer_modify);
        Map<String, String> map = new HashMap<>();
        map.put("id", mEditCustomerItem.getId());
        map.put("name", mEtEditAddName.getText().toString().trim());
        map.put("remark", mEtEditAddRemark.getText().toString().trim());
        map.put("org", mEtEditAddCompany.getText().toString().trim());
        if (null != mGroupItem) {
            map.put("groupId", mGroupItem.getGroupId());
        } else {
            map.put("groupId", mEditCustomerItem.getGroupId());
        }
        data.setParameters(map);
        request(data, AppSupplyRouterConstant.cmd_account_customer_modify, onRequestListener);
    }

    OnRequestListener<SaveModifyEntity> onRequestListener = new OnRequestListener<SaveModifyEntity>() {
        @Override
        public SaveModifyEntity jsonToObj(String responseStr) {
            return new Gson().fromJson(responseStr, SaveModifyEntity.class);
        }

        @Override
        public void onFail(int failCode, Object arg, Object tag) {


        }

        @Override
        public void onResponseError(int failCode, Object arg, Object tag) {
        }

        @Override
        public void onStart(Object tag) {

        }

        @Override
        public void onResponse(ResponseEntity<SaveModifyEntity> response, Object tag) {
            SaveModifyEntity responseElement = response.getResponseElement();
            if (responseElement.isSuccess()) {
                toast("修改成功");
                // 保存成功 返回到客户详情页面
                //RxBus.post(ARouter.BUS_GET_CUSTOMER_ITEM, saveEntity.getCustomer());
                Intent intent = new Intent();
                intent.putExtra("customerItem", responseElement.getCustomer());
                setResult(0x001,intent);
                finish();
                return;
            }
            T.toast("修改出现异常，请稍后再试");
        }
    };

    private void intoDelivery() {
        //收货地址
        switch (mAction) {
            case CUSTOMER_DETAIL_ACTIVITY:
                mAccountId = mEditCustomerItem.getAccountId();
                break;
        }
        Intent intent = new Intent(this, CustomerDeliveryActivity.class);
        intent.putExtra("accountId", mAccountId);
        startActivity(intent);
    }


}
